import { CachedToken } from "@/utils/cached"
import { RouterProvider } from "@/router/RouterProvider"
import { useAtom } from "jotai"
import { useEffect, useState } from "react"
import { Bounce, ToastContainer } from "react-toastify"
import { useUserInfo } from "./features/business/HomePage_deprecated"
import ThemeLayout from "./layouts/ThemeLayout"
import {
    loadHomeGameAtom,
    useFavoriteGame,
    useUserWallet,
} from "./features/business/HomePage_deprecated/atoms_deprecated"
import { createLogger } from "./utils/logger"
const logger = createLogger("ApiFetchers")

function App() {
    const { getUserInfo, clearUserInfo } = useUserInfo()
    const { getUserWallet, clearUserWallet } = useUserWallet()
    const { getFavoriteGameList, clearFavorite } = useFavoriteGame()
    const [, loadHomeData] = useAtom(loadHomeGameAtom)
    const [isLoggedIn, setIsLoggedIn] = useState<boolean>(false)
    useEffect(() => {
        loadHomeData()
        const unsubscribe = CachedToken._signals.token.subscribe(({ accessToken }) => {
            const logged = Boolean(accessToken)
            setIsLoggedIn(logged)
            logger.debug("Token 已经更新:", accessToken)
            if (accessToken) {
                getUserInfo()
                getUserWallet()
                getFavoriteGameList()
            } else {
                clearUserInfo()
                clearUserWallet()
                clearFavorite()
            }
        })
        return () => {
            unsubscribe()
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    useEffect(() => {
        if (!isLoggedIn) return
        const interval = setInterval(() => {
            getUserInfo()
        }, 270000)
        return () => {
            clearInterval(interval)
        }
    }, [isLoggedIn, getUserInfo])

    return (
        <ThemeLayout>
            <ToastContainer
                position="top-center"
                autoClose={5000}
                hideProgressBar={false}
                newestOnTop={false}
                closeOnClick={false}
                rtl={false}
                pauseOnFocusLoss
                draggable
                pauseOnHover
                theme="light"
                transition={Bounce}
            />
            <RouterProvider />
        </ThemeLayout>
    )
}

export default App
